package cn.nfwx.tv.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.MessageQueue;
import android.os.StatFs;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ContextThemeWrapper;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.mcxiaoke.packer.helper.PackerNg;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXVideoObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;
import java.util.Stack;

import cn.nfwx.tv.R;
import cn.nfwx.tv.activity.HomeActivity;
import cn.nfwx.tv.base.NFWXApplication;
import cn.nfwx.tv.helper.AccountHelper;
import cn.nfwx.tv.helper.ValueCallback;
import cn.nfwx.tv.okhttp.UrlHelper;

/**
 * Created by zb.liu on 2017/11/17.
 */

public class AppUtil {

    private AppUtil() {
    }

    /**
     * 是否安装微信
     *
     * @param context
     * @return
     */
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }

        return false;
    }

    public static int getCrrentVersion(Context context) {
        int currentVersion = 1;
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            currentVersion = pi.versionCode;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return currentVersion;
    }

    public static String getCrrentName(Context context) {
        String versionName = "1.0.0";
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    /**
     * 获取渠道标识
     *
     * @param context
     * @return
     */
    public static String getChannel(Context context) {
        Context appContent = context.getApplicationContext();
        String channel = PackerNg.getChannel(context);
        if (TextUtils.isEmpty(channel)) {
            channel = "southtv";
            ApplicationInfo appInfo = null;
            try {
                appInfo = appContent.getPackageManager().getApplicationInfo(appContent.getPackageName(), PackageManager.GET_META_DATA);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            if (appInfo != null) {
                channel = appInfo.metaData.get("UMENG_CHANNEL") + "";
            }
        }
        return channel;
    }

    /**
     * 根据IP地址获取MAC地址
     *
     * @return
     */
    public static String getLocalMacAddressFromIp() {
        String strMacAddr = null;
        try {
            //获得IpD地址
            InetAddress ip = getLocalInetAddress();
            byte[] b = NetworkInterface.getByInetAddress(ip).getHardwareAddress();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < b.length; i++) {
                if (i != 0) {
                    buffer.append(':');
                }
                String str = Integer.toHexString(b[i] & 0xFF);
                buffer.append(str.length() == 1 ? 0 + str : str);
            }
            strMacAddr = buffer.toString();
        } catch (Exception e) {

        }

        return strMacAddr;
    }

    /**
     * 获取移动设备本地IP
     *
     * @return
     */
    public static InetAddress getLocalInetAddress() {
        InetAddress ip = null;
        try {
            //列举
            Enumeration<NetworkInterface> en_netInterface = NetworkInterface.getNetworkInterfaces();
            while (en_netInterface.hasMoreElements()) {//是否还有元素
                NetworkInterface ni = (NetworkInterface) en_netInterface.nextElement();//得到下一个元素
                Enumeration<InetAddress> en_ip = ni.getInetAddresses();//得到一个ip地址的列举
                while (en_ip.hasMoreElements()) {
                    ip = en_ip.nextElement();
                    if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1)
                        break;
                    else
                        ip = null;
                }

                if (ip != null) {
                    break;
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ip;
    }

    /**
     * Get activity from context object
     *
     * @param context something
     * @return object of Activity or null if it is not Activity
     */
    public static Activity scanForActivity(Context context) {
        if (context == null) return null;
        if (context instanceof Activity) {
            return (Activity) context;
        } else if (context instanceof ContextWrapper) {
            return scanForActivity(((ContextWrapper) context).getBaseContext());
        }
        return null;
    }

    /**
     * Get AppCompatActivity from context
     *
     * @param context
     * @return AppCompatActivity if it's not null
     */
    public static AppCompatActivity getAppCompActivity(Context context) {
        if (context == null) return null;
        if (context instanceof AppCompatActivity) {
            return (AppCompatActivity) context;
        } else if (context instanceof ContextThemeWrapper) {
            return getAppCompActivity(((ContextThemeWrapper) context).getBaseContext());
        }
        return null;
    }

    /**
     * 分享video到微信
     *
     * @param context
     * @param wxSceneSession
     * @param url
     * @param title
     * @param bitmap
     */
    public static void shareVideo2WeiXin(Context context, final int wxSceneSession, String url, String title, String des, Bitmap bitmap) {
        if (NFWXApplication.getInstance().getIwxapi().isWXAppInstalled()) {
            WXVideoObject video = new WXVideoObject();
            video.videoUrl = url;
            WXMediaMessage msg = new WXMediaMessage(video);
            msg.title = title;
            msg.setThumbImage(bitmap);
            msg.description = des;
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = msg;
            req.scene = wxSceneSession;
            NFWXApplication.getInstance().getIwxapi().sendReq(req);
            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            }
        } else {
            ToastUtil.show(context, "没有安装微信");
        }
    }

    /**
     * 分享Web到微信
     *
     * @param context
     * @param wxSceneSession
     * @param url
     * @param title
     * @param des
     * @param bitmap
     */
    public static void shareWebPage2WeiXin(Context context, final int wxSceneSession, String url, String title, String des, Bitmap bitmap) {
        if (NFWXApplication.getInstance().getIwxapi().isWXAppInstalled()) {
            WXWebpageObject webpageObject = new WXWebpageObject();
            webpageObject.webpageUrl = url;
            WXMediaMessage mediaMessage = new WXMediaMessage();
            mediaMessage.mediaObject = webpageObject;
            mediaMessage.setThumbImage(bitmap);
            mediaMessage.title = title;
            mediaMessage.description = des;
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = String.valueOf(System.currentTimeMillis());
            req.message = mediaMessage;
            req.scene = wxSceneSession;
            NFWXApplication.getInstance().getIwxapi().sendReq(req);
            if (!bitmap.isRecycled()) {
                bitmap.recycle();
            }
        } else {
            ToastUtil.show(context, "没有安装微信");
        }
    }

    /**
     * 获取sign
     *
     * @param path
     * @param time
     * @return
     */
    public static String getSign(String path, long time) {
        String sign = path.replace("http://", "");
        sign = sign.replace("https://", "");
        int index = sign.indexOf("/");
        sign = sign.substring(index);
        StringBuffer stringBuffer = new StringBuffer(sign);
        if (sign.contains("?")) {
            if (sign.contains("&")) {
                stringBuffer.append("&uid=").append(AccountHelper.getInstance().getUid(NFWXApplication.getInstance()));
            } else {
                stringBuffer.append("uid=").append(AccountHelper.getInstance().getUid(NFWXApplication.getInstance()));
            }
            stringBuffer.append("&t=").append(time);
            stringBuffer.append("&ip=").append(AccountHelper.getInstance().getIp());
            stringBuffer.append("&key=").append(AccountHelper.getInstance().getKey());
        } else {
            stringBuffer.append("?uid=").append(AccountHelper.getInstance().getUid(NFWXApplication.getInstance()));
            stringBuffer.append("&t=").append(time);
            stringBuffer.append("&ip=").append(AccountHelper.getInstance().getIp());
            stringBuffer.append("&key=").append(AccountHelper.getInstance().getKey());
        }
        sign = stringBuffer.toString();
        sign = MD5Util.MD5(sign);
        return TextUtils.isEmpty(sign) ? sign : sign.toLowerCase();
    }

    /**
     * 解决内存泄漏
     *
     * @param context
     */
    public static void fixLeakCanary696(Context context) {
//        if (!OSUtils.isEmui()) {
//            LogUtil.e("ttt", "isEmui---false");
//            return;
//        }
        try {
            Class clazz = Class.forName("android.gestureboost.GestureBoostManager");

            Field _sGestureBoostManager = clazz.getDeclaredField("sGestureBoostManager");
            _sGestureBoostManager.setAccessible(true);
            Field _mContext = clazz.getDeclaredField("mContext");
            _mContext.setAccessible(true);

            Object sGestureBoostManager = _sGestureBoostManager.get(null);
            if (sGestureBoostManager != null) {
                _mContext.set(sGestureBoostManager, context);
            }
        } catch (Exception ignored) {

        }
    }

    /**
     * InputMethodManager内存泄漏修复，无法释放activity
     *
     * @param destContext
     */
    public static void fixInputMethodManagerLeak(Context destContext) {
        if (destContext == null) {
            return;
        }

        InputMethodManager imm = (InputMethodManager) destContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }

        String[] arr = new String[]{"mCurRootView", "mServedView", "mNextServedView", "mLastSrvView"};
        Field f = null;
        Object obj_get = null;
        for (int i = 0; i < arr.length; i++) {
            String param = arr[i];
            try {
                f = imm.getClass().getDeclaredField(param);
                if (f.isAccessible() == false) {
                    f.setAccessible(true);
                } // author: sodino mail:sodino@qq.com
                obj_get = f.get(imm);
                if (obj_get != null && obj_get instanceof View) {
                    View v_get = (View) obj_get;
                    if (v_get.getContext() == destContext) { // 被InputMethodManager持有引用的context是想要目标销毁的
                        f.set(imm, null); // 置空，破坏掉path to gc节点
                    } else {
                        break;
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }



    /**
     * 获得机身内存总大小
     *
     * @return
     */
    public static int getRomTotalSize(Context context) {
        ActivityManager manager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        int largeHeap = manager.getLargeMemoryClass();
        return largeHeap;
    }

    /**
     * 获得机身可用内存
     *
     * @return
     */
    public static String getRomAvailableSize(Context context) {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return Formatter.formatFileSize( context.getApplicationContext(), blockSize * availableBlocks);
    }

    /**
     * 内存泄漏
     * @param looper
     */
    public static void flushStackLocalLeaks(Looper looper) {
        final Handler handler = new Handler(looper);
        handler.post(new Runnable() {
            @Override public void run() {
                Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
                    @Override public boolean queueIdle() {
                        handler.sendMessageDelayed(handler.obtainMessage(), 1000);
                        return true;
                    }
                });
            }
        });
    }
}
